﻿using System;
using System.Collections.Generic;
using System.Text;
using Studio.Network.Utilities;
using System.Net;
using Studio.Network.Kaixin001.Entities;
using Studio.Foundation.Text;

namespace Studio.Network.Kaixin001
{
    public class ResponseThread
    {
        int threadid;
        string server;
        int timeout = 10000;


        public static readonly long RESPONSE_FAILED = long.MaxValue;

        /// <summary>
        /// Time Consumed by Seek
        /// </summary>
        protected long responseTime = RESPONSE_FAILED;

        public long ResponseTime
        {
            get { return responseTime; }
            set { responseTime = value; }
        }

        public ResponseThread(int threadid, int timeout, string server)
        {
            this.timeout = timeout;
        }

        public string RequestHeader
        {
            get
            {
                string HeaderTemplate = "POST / HTTP/1.1\r\n" +
                            "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/xaml+xml, */*\r\n" +
                            "Accept-Language: en-us\r\n" +
                            "Accept-Encoding: deflate\r\n" +
                            "x-prototype-version: 1.4.0\r\n" +
                            "Content-Type: application/x-www-form-urlencoded\r\n" +
                            "UA-CPU: x86\r\n" +
                            "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727)\r\n" +
                            "Host: {0}\r\n" +
                            "Connection: Keep-Alive\r\n\r\n";
                return string.Format(HeaderTemplate, KXInterface.HOST);
            }
        }

        public void Seek()
        {
            HttpHelper http = new HttpHelper();
            http.ResponseEncoding = Encoding.UTF8;
            http.Timeout = this.timeout;

            // Save start time
            long start = DateTime.Now.Ticks;
            string response = http.AdvancedRequest(server, 80, this.RequestHeader);
            // Compute interval
            if (response.ToUpper().StartsWith("HTTP"))
                responseTime = DateTime.Now.Ticks - start;
            else
                responseTime = RESPONSE_FAILED;
            Console.WriteLine(string.Format("{0:D2}.SERVER[{1}]\tRT[{2}]", threadid, server, responseTime));
        }
    }
}
